package com.mar.tech.unify;

import io.vertx.core.DeploymentOptions;
import io.vertx.core.Launcher;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.impl.cpu.CpuCoreSensor;
import io.vertx.core.logging.SLF4JLogDelegateFactory;
import io.vertx.ext.dropwizard.DropwizardMetricsOptions;
import io.vertx.ext.dropwizard.Match;
import io.vertx.ext.dropwizard.MatchType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME;

/**
 * Description: 启动 Launcher .<br>
 *
 * @author m-xy
 *   Created By 2020/4/2 12:14
 */
public class MainLauncher extends Launcher {
  private final static Logger logger = LoggerFactory.getLogger(MainLauncher.class);

  public static void main(String[] args) {
    System.setProperty(LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName());
    new MainLauncher().dispatch(args);
  }

  /**
   * 启动前准备阶段.
   *
   * @param options 参数
   */
  @Override
  public void beforeStartingVertx(VertxOptions options) {
    logger.info("[Vert.x] Vert.x Options Ready");
    options.setPreferNativeTransport(true);
    // 也可以通过 -Dvertx.metrics.options.enabled=true 启动监控
    options.setMetricsOptions(
      new DropwizardMetricsOptions()
        .setEnabled(true)
        .setRegistryName("unify-metrics")
        .addMonitoredHttpServerUri(
          new Match().setValue("/*").setType(MatchType.REGEX))
    );
    options.setWorkerPoolSize(CpuCoreSensor.availableProcessors() * 20);
    super.beforeStartingVertx(options);
  }

  /**
   * Vert.x启动完成阶段.
   *
   * @param vertx
   */
  @Override
  public void afterStartingVertx(Vertx vertx) {
    logger.info("[Vert.x] Starting Vert.x (JVM running for you)");
    super.afterStartingVertx(vertx);
  }

  /**
   * Vert.x停止阶段.
   */
  @Override
  public void afterStoppingVertx() {
    logger.info("[Vert.x] Stopping Vert.x (JVM running for you)");
    super.afterStoppingVertx();
  }

  /**
   * 部署失败时，此方法会被调用。您可以重写此方法来自定义行为。
   * 默认情况下，它关闭`vertx`实例。
   *
   * @param vertx             vert.x 实例
   * @param mainVerticle      verticle
   * @param deploymentOptions verticle 部署参数
   * @param cause             部署失败的原因
   */
  @Override
  public void handleDeployFailed(
    Vertx vertx, String mainVerticle, DeploymentOptions deploymentOptions, Throwable cause) {
    logger.error("[Vert.x] Start Vert.x Failed", cause);
    super.handleDeployFailed(vertx, mainVerticle, deploymentOptions, cause);
  }
}
